import { success, fail, interceptDomain } from "../utils/base";
import { getBDCConfig, getOtherDbData } from "../utils/lokijs-db-server";

export default defineEventHandler(async (event) => {
  interceptDomain(event);
  // 获取请求参数 post
  // const body = await readBody(event);
  // 获取 LokiJS 实例
  const db = event.context.db;
  // 1. 读取配置文件
  const { configData, configPath } = getBDCConfig();
  // 2. 获取其他数据库
  let instanceList: any = [];
  if (configData.dbs && configData.dbs.length > 0) {
    configData.dbs.forEach((e: any) => {
      if (e.path != db.filename) {
        instanceList.push(e);
        console.log("3.1 查询数据库:", e.path);
      }
    });
  }

  // 3. 查询
  if (db) {
    // 3.1 获取数据源
    let dbData = db.getCollection("analyticsEvent");
    if (!dbData) dbData = { data: [] };
    // 3.2 拷贝数据
    let dbDataCopy = JSON.parse(JSON.stringify(dbData.data));
    // 3.2.1 增加数据库标识,用于删除
    dbDataCopy = dbDataCopy.map((el: any) => {
      el.dbName = db.filename;
      return el;
    });

    // 获取其他数据源
    const { data: otherDatas } = (await getOtherDbData(
      instanceList,
      "analyticsEvent"
    )) as any;
    console.log(
      dbDataCopy.length,
      "获取其他数据源 otherDatas:",
      otherDatas.length
    );
    let totalData = dbDataCopy.concat(otherDatas);
    return success(totalData);
  } else {
    return fail("db 不存在,暂无数据");
  }
});
